package com.eobard.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.eobard.exception.CustomException;
import com.eobard.utils.ResponseUtils;
import com.eobard.utils.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Eobard_Thawne
 * @version 1.0
 * @date 2022/8/6 -17:26
 */

/**
 * 登录失败处理器类
 */
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {

    /**
     * 当登录失败时,将登陆失败的原因通过JSON返回给前端
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message = null;
        int code=500;

        //判断用户登录失败的异常类型
        if(exception instanceof AccountExpiredException){
            message="账户过期,登陆失败";
        }else if(exception instanceof BadCredentialsException){
            message="用户名或密码错误,登陆失败";
        }else if(exception instanceof CredentialsExpiredException){
            message="密码过期,登陆失败";
        }else if(exception instanceof DisabledException){
            message="账户被禁用,登陆失败";
        }else if(exception instanceof LockedException){
            message="账户被锁,登陆失败";
        }else if(exception instanceof InternalAuthenticationServiceException){
            message="账户不存在,登陆失败";
        }else if(exception instanceof CustomException){
            message=exception.getMessage();
            code=600;
        }else {
            message="登录失败";
        }
        //返回登陆失败原因
        String result=JSON.toJSONString(Result.error().code(code).message(message), SerializerFeature.DisableCircularReferenceDetect);

//        //设置响应编码格式
//        response.setContentType("application/json;charset=utf-8");
//        //获取输出流,并返回前端JSON数据
//        ServletOutputStream outputStream = response.getOutputStream();
//        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
//        outputStream.flush();
//        outputStream.close();

        //通过流对象输出JSON到前端
        ResponseUtils.writeJSON(result,response);

    }
}
